using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Serilog.Core;
using WebapiDemo.Domain.Entity;
using WebapiDemo.Domain.Repository;
using WebapiDeom.Infrastructure.Utils;

namespace WebapiDemo.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UserController : ControllerBase
    {
        //日志和编码序列化_logger
        private readonly ILogger<UserController> _logger;
        private readonly IRepositoryBase<Users> _usersRes;
        public UserController(IRepositoryBase<Users> usersRes, ILogger<UserController> logger)
        {
            _logger= logger; 
            _usersRes = usersRes;
        }

        [HttpGet]
        public IEnumerable<dynamic> Index()
        {
            _usersRes.Add(new Users
            {
                UserName = "aaa",
                Password = "123"
            });
            // 返回指定字段用select
            var lst = _usersRes.Table.Select(x=>new{x.Id,x.UserName,x.Password,x.IsDeleted}).ToArray();
            _logger.LogInformation(lst.SerializeObject());
            return lst;
        }
        [HttpPost]
        public Users AddUser(UserCto model)
        {
            var tmp = new Users
            {
                UserName = model.UserName,
                Password = model.Password
            };
            _usersRes.Add(tmp);
            return tmp;
        }

        public class UserCto
        {
            public string UserName { get; set; }
            public string Password { get; set; }
        }
        [HttpPut]
        [Route("{id}")]
        public Users UpdateUser(Guid id, UserCto model)
        {
            var entity = _usersRes.GetById(id);
            if (entity != null)
            {
                entity.Password = model.Password;
                _usersRes.Update(entity);
            }
            return entity;
        }
        [HttpDelete]
        [Route("{id}")]
        public dynamic DeleteUser(Guid id)
        {
            _usersRes.Delete(id);
            return new
            {
                code = 1000,
                msg = "删除成功",
                Data = ""
            };
        }
    }
}